package com.ma.a05;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName ComponentScanPostProcessor
 * @Author: mayongqiang
 * @DATE 2022/4/1 19:59
 * @Description: 自定义分析@ComponentScan注册bean
 */

public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {
    // context.refresh()
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {


        /* 模拟工厂后处理器 进行组件扫描补充到BeanFactory
         * 1、通过AnnotationUtils工具类找到指定类上的@ComponentScan
         * 2、找@ComponentScan的basePackages，转换为路径，将路径下的类二进制文件读取进resource中
         * 3、分析每个资源的类名，是否带@Component注解及其派生注解
         * 4、如果有这两类注解，那么就更具类名生成对应的BeanDefinition 和 bean的名字
         * 5、根据[BeanName,BeanDefinition]注册进beanFactory中
         *  */
        ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);

        try {
            if (componentScan != null) {
                for (String basePackage : componentScan.basePackages()) {
                    String path = "classpath*:" + basePackage.replace(".", "/") + "/**/*.class";
                    CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                    AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path);
                    for (Resource resource : resources) {
                        MetadataReader reader = factory.getMetadataReader(resource);
                        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();

                        if (annotationMetadata.hasAnnotation(Component.class.getName())
                                || annotationMetadata.hasMetaAnnotation(Component.class.getName())) {
                            AbstractBeanDefinition bd = BeanDefinitionBuilder
                                    .genericBeanDefinition(reader.getClassMetadata().getClassName())
                                    .getBeanDefinition();

                            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) configurableListableBeanFactory;
                            String beanName = generator.generateBeanName(bd, beanFactory);
                            beanFactory.registerBeanDefinition(beanName, bd);


                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
